import { FILE_UPLOAD_URL, SESSION_KEY, CODE_KEY, USER_INFO } from './constant.js'
import { login } from '../api/auth.js'

const mockUrl = FILE_UPLOAD_URL

const request = async (url, options) => {
	try {
		const token = uni.getStorageSync(SESSION_KEY)
		let header = {}
		if (token) {
			header.Authorization = `wx ${token}`
		}
		let paramPath = ''
		if (options && options.params) {
			let index = 0
			for (const [key, value] of Object.entries(options.params)) {
				paramPath += `${index === 0 ? '?' : '&'}${key}=${value}`
				index++
			}
		}
		const res = await uni.request({
			url: mockUrl + url + paramPath,
			...options,
			header
		})
		if (res.statusCode !== 200) {
			throw new Error('请求失败')
		}
		const { code, data, msg } = res.data
		if (code !== 200) {
			throw new Error(msg)
		}
		if (msg) {
			uni.showToast({
				title: msg
			})
		}
		return {
			success: true,
			data
		}
	} catch (err) {
		console.log(err)
		return {
			success: false
		}
	}
}

export const fetchUserToken = () => {
	uni.login({
		provider: 'weixin',
		async success ({ code }) {
			uni.setStorageSync(CODE_KEY, code)
			const { success, data } = await login(code)
			const { token, user } = data
			uni.setStorageSync(SESSION_KEY, token)
			uni.setStorageSync(USER_INFO, user)
		}
	})
} 

export default request